using System.Collections.Generic;
using System.Windows.Forms;
using Lizk.SimpleHUD;
using System.IO;
using System;
using System.Drawing;
using Lizk.Utilities;

namespace SharpMedia.Input
{
    public delegate void CommandEvent(object sender, HUDCommands command);

    /// <summary>
    /// Fires HUDCommands
    /// </summary>
    public class FormInputController
    {
        InputSettings settings;
        Form form;
        string configFile;

        public event EventHandler<CommandEventArgs> FireCommand;

        public string ConfigFile
        {
            get { return configFile; }
            set { configFile = value; }
        }

        public FormInputController(string configFile, Form form)
        {
            this.configFile = configFile;
            this.form = form;
            
            InputSettings.TryLoadSettings(configFile, out settings);

            form.KeyDown += new KeyEventHandler(KeyDown);
            form.MouseWheel += new MouseEventHandler(MouseWheel);
            form.KeyPress += new KeyPressEventHandler(form_KeyPress);
        }


        void form_KeyPress(object sender, KeyPressEventArgs e)
        {
            foreach (var binding in settings.Bindings)
            {
                if (binding.Command != HUDCommands.Back && binding.Command != HUDCommands.Select)
                    continue;
                if (((int)binding.Primary == e.KeyChar && binding.PrimaryMods == Keys.None) || ((int)binding.Secondary == e.KeyChar && binding.SecondaryMods == Keys.None))
                {
                    return;
                }
            }

            if (Form.ActiveForm == form && FireCommand != null)
            {
                FireCommand(this, new CommandEventArgs(HUDCommands.KeyPress, e.KeyChar));
            }
        }

        private void KeyDown(object sender, KeyEventArgs e)
        {
            if (Form.ActiveForm == form && FireCommand != null)
            {
                foreach (var binding in settings.Bindings)
                {
                    if ((binding.Primary == e.KeyCode && binding.PrimaryMods == e.Modifiers) || (binding.Secondary == e.KeyCode && binding.SecondaryMods == e.Modifiers))
                    {
                        FireCommand(this, new CommandEventArgs(binding.Command));
                        e.Handled = true;
                        break;
                    }
                }
            }

        }


        private void MouseWheel(object sender, MouseEventArgs e)
        {
            if (e.Delta > 0 && Form.ActiveForm == form && FireCommand != null)
            {
                FireCommand(this, new CommandEventArgs(HUDCommands.Up));
            }
            if (e.Delta < 0 && Form.ActiveForm == form && FireCommand != null)
            {
                FireCommand(this, new CommandEventArgs(HUDCommands.Down));
            }
        }
    
    
    }

}
